'use strict';

angular.module('xuexibangApp')
	.controller('StudentCtrl', function($scope, $http, Klass, User) {
		$scope._id="";
		$scope.password="";
		$scope.klasses = Klass.query();
		$scope.selKlass = function(klass, $event) {
			$scope.klass = klass;
			//console.log(klass);
			$scope.students = User.students({
				klass: $scope.klass.code
			});
			$("#klassmenu .active").toggleClass("active");
			$($event.target).toggleClass("active");
		}
		$scope.edit = function(student) {
			$scope._id = student._id;
			$scope.code = student.code;
			$scope.name = student.name;
		}
		$scope.save = function(form) {
			$scope.submitted = true;
			if (form.$valid) {
				var user = {
					code: $scope.code,
					name: $scope.name,
					klass: $scope.klass.code,
					role: ['student'],
					setpass: $scope.setpass,
					password: $scope.password
				}
				if ($scope._id != "") {
					user._id = $scope._id;
				};
				console.log(user);
				User.save(user, function(data) {
					var user = data;
					if ($scope._id === "") {
						$scope.students.push(user);
					} else {
						for (var i = 0; i < $scope.students.length; i++) {
							if ($scope.students[i]._id === user._id) {
								$scope.students[i] = user;
								break;
							}
						}
					}
					nullinput();
				}, function(err) {
					console.log(err);
				});
			}
		};
		$scope.reset = nullinput;
		function nullinput() {
			$scope._id = $scope.code = $scope.name = "";
			$scope.setpass = false;
			$scope.password = "";
			$scope.submitted = false;
		}
		$scope.delete = function(user) {
			User.remove({
				id: user._id
			},function(data){
				//console.log(data);
				angular.forEach($scope.students, function(u, i) {
					if (u === user) {
						$scope.students.splice(i, 1);
					}
				});
			},function(err){
				console.log(err);
			});
		};
	});
